package cloud.keveri.gateway.plugin.call;

import cloud.keveri.gateway.dto.Rule;
import cloud.keveri.gateway.dto.invoker.ServiceInvoker;
import cloud.keveri.gateway.plugin.api.KeveriPluginChain;
import cloud.keveri.gateway.plugin.api.context.GatewayContext;
import cloud.keveri.gateway.plugin.base.AbstractKeveriPlugin;
import cloud.keveri.gateway.plugin.call.proxy.DubboProxyService;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static cloud.keveri.gateway.plugin.base.def.Const.*;

public class RemoteCallPlugin extends AbstractKeveriPlugin {

    private final DubboProxyService dubboProxyService;

    public RemoteCallPlugin(DubboProxyService dubboProxyService) {
        this.dubboProxyService = dubboProxyService;
    }

    @Override
    public int getOrder() {
        return PLUGIN_CALL_ORDER;
    }

    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, KeveriPluginChain chain) {
        // 1. 提取上下文和参数
        GatewayContext context = exchange.getAttribute(CONTEXT);
        String param = exchange.getAttribute(PARAM_TRANSFORM);

        // 2. 提取路由规则
        assert context != null;
        Rule rule = context.getRule();
        ServiceInvoker invoker = context.getInvoker();

        // 3. 发起调用
        final Mono<Object> result = dubboProxyService.genericInvoker(param, invoker, exchange);
        return result.then(chain.execute(exchange));
    }
}
